import argparse
import os
from dyva.batch_analyzer import VideoBatchAnalyzer
from dotenv import load_dotenv
import json

def parse_args():
    load_dotenv()
    defaults = {
        "input_dir": "S:\\",
        "output_dir": "results",
        "config": "config\\categories_example.txt",
        "api_key": None,
        "workers": 5
    }
    if os.path.exists(".config"):
        try:
            with open(".config", "r", encoding="utf-8") as f:
                conf = json.loads(f.read())
            for k in defaults:
                if k in conf and conf[k] is not None:
                    defaults[k] = conf[k]
        except Exception:
            pass
    p = argparse.ArgumentParser(description='抖音视频批量分析')
    p.add_argument('--input-dir', default=defaults["input_dir"], help='视频目录')
    p.add_argument('--output-dir', default=defaults["output_dir"], help='输出目录')
    p.add_argument('--config', default=defaults["config"], help='类目表配置文件路径')
    p.add_argument('--api-key', default=defaults["api_key"], help='智谱 API Key（可用环境变量 ZHIPU_API_KEY 替代）')
    p.add_argument('--workers', type=int, default=defaults["workers"], help='并发线程数，建议 ≤ 5')
    return p.parse_args()

def main():
    args = parse_args()
    os.makedirs(args.output_dir, exist_ok=True)
    analyzer = VideoBatchAnalyzer(config_path=args.config, api_key=args.api_key, workers=args.workers)
    result = analyzer.process_directory(directory_path=args.input_dir, output_dir=args.output_dir)
    total = len(result['success']) + len(result['failed'])
    print(f"处理完成：成功 {len(result['success'])} / 失败 {len(result['failed'])} / 总计 {total}")
    if result['failed']:
        print(f"失败清单已生成：{os.path.join(args.output_dir, 'failed_list.txt')}")

if __name__ == '__main__':
    main()

